#!/usr/bin/python
# -*- coding: utf-8 -*-

""" 
-------------------------------------------------
@version    : v1.0 
@author     : fangzheng
@contact    : zfang@hillinsight.com
@software   : PyCharm 
@filename   : hivehelper.py
@create time: 2019/3/26 22:02 
@describe   : 
@use example: python hivehelper.py [param1 param2]
-------------------------------------------------
"""
from IDBHelper import DBHelper
from logger import Logger
from dbutils import select,execute,DBConfig
from pyhive import hive

log = Logger(name='hivehelper')

class HiveHelper(DBHelper):
    """
    HiveHelper
    """
    _connect = None

    def __init__(self, db_config):
        self.init(db_config)

    def init(self, db_config):
        """
        init database connection
        :param dbconfig:
        :return: True/False
        """
        try:
            dbconfig = DBConfig(db_config)
            self._connect = hive.Connection(
                host=str(dbconfig.host),
                port=dbconfig.port,
                database=str(dbconfig.db),
                username=str(dbconfig.username))
            log.info(" Connected to Hive database [ {db} ]".format(db=dbconfig.db))
            return True
        except Exception as e:
            log.error(" Connect Hive exception : \n{e}\n".format(e=str(e)))
            return False

    def get_conn(self):
        if self._connect:
            return self._connect
        else:
            self.init()
            return self._connect

    def close_conn(self):
        if self._connect:
            self._connect.close()
            log.info(" Hive database connection closed....")

    def table_is_exist(self,table_name):
        """
        Check table is exist
        :param tablename:
        :return:
        """
        tablename = (str(table_name),)
        rows = self.select(sql="show tables")
        is_exist = rows.count(tablename)
        if is_exist >= 1:
            return True
        else:
            return False


    def select(self, sql, param=None , size=None):
        """
        Query data
        :param sql:
        :param param:
        :param size: Number of rows of data you want to return
        :return:
        """
        # try:
        #     cursor = self._connect.cursor()
        #     cursor.execute(sql)
        #     if size:
        #         rows = cursor.fetchmany(size)
        #     else:
        #         rows = cursor.fetchall()
        #     log.debug(""" Hive SQL as follows , Result total [ {lines} ] lines：\n{sql}""".format(
        #         lines=len(rows),
        #         sql=sql))
        # except Exception as e:
        #     log.error(" 执行Hive SQL发生了异常 \n{e}\n".format(e=e.args[0].status.errorMessage))
        # finally:
        #     if cursor:
        #         cursor.close()
        # return rows
        return select(self._connect, sql, param, size)

    def execute(self,sql, param=None):
        """
        exec DML：INSERT、UPDATE、DELETE
        :param sql: dml sql
        :param param: string|list
        :return: Number of rows affected
        """
        return execute(self._connect, sql, param)
